#!/bin/sh
case "$1" in
  start)
    # GFLT300 and beyond will use hnvram with 1ST_SERIAL_NUMBER variable.
    # GFLT110 uses legacy sysvar_cmd with SERIAL_NO variable.
    if [ -e /dev/mtd/hnvram ]; then
      SERIAL=$(hnvram -qr 1ST_SERIAL_NUMBER)
    else
      SERIAL=$(hnvram -qr SERIAL_NO)
    fi
    [ -n "$SERIAL" ] &&
      echo "$SERIAL" >/etc/serial &&
      chmod 444 /etc/serial

    # The serial number needs to match the given format, otherwise sycl will
    # complain.
    PARSED_SERIAL=$(parse_sn "$SERIAL")
    if [ "$PARSED_SERIAL" = "sn__deadbeef" ]; then
      echo "Optical link may not come up! Serial number does not match" \
        "expected format: 4 char prefix with an 8 hex char suffix, got:" \
        "'$SERIAL'"
    fi

    # Do this before gpio-mailbox
    update-gpio-links

    babysit 60 gpio-mailbox 2>&1 | logos gpio-mailbox &
    ;;
  stop)
    pkillwait -x gpio-mailbox
    ;;
  restart)
    $0 stop; $0 start
    ;;
  *)
    echo "Usage: $0 {start|stop|restart}"
    exit 1
    ;;
esac
